<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px" class="query-form">
      <el-form-item label="商户订单号" prop="outTradeNo">
        <el-input
          v-model="queryParams.outTradeNo"
          placeholder="请输入商户订单号"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信订单号" prop="transactionId" v-if="activeTab === 'wechat'">
        <el-input
          v-model="queryParams.transactionId"
          placeholder="请输入微信订单号"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付宝订单号" prop="transactionId" v-if="activeTab === 'alipay'">
        <el-input
          v-model="queryParams.transactionId"
          placeholder="请输入支付宝订单号"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入商品描述"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 120px">
          <el-option label="全部状态" value="" />
          <el-option label="待支付" value="0" />
          <el-option label="支付成功" value="1" />
          <el-option label="支付失败" value="2" />
          <el-option label="已退款" value="3" />
          <el-option label="已关闭" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 200px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['payment:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="微信订单" name="wechat">
        <el-table v-loading="loading" :data="orderList">
          <el-table-column label="商户订单号" align="center" prop="outTradeNo" width="200" show-overflow-tooltip />
          <el-table-column label="微信订单号" align="center" prop="transactionId" width="280" show-overflow-tooltip />
          <el-table-column label="商品描述" align="center" prop="description" width="150" show-overflow-tooltip />
          <el-table-column label="订单金额" align="center" prop="totalAmount" width="100">
            <template slot-scope="scope">
              <span>¥{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center" prop="status" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === '0'" type="warning">待支付</el-tag>
              <el-tag v-else-if="scope.row.status === '1'" type="success">支付成功</el-tag>
              <el-tag v-else-if="scope.row.status === '2'" type="danger">支付失败</el-tag>
              <el-tag v-else-if="scope.row.status === '3'" type="info">已退款</el-tag>
              <el-tag v-else-if="scope.row.status === '4'" type="info">已关闭</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="支付时间" align="center" prop="payTime" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.payTime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['payment:order:query']"
              >详情</el-button>
              <el-button
                v-if="scope.row.status === '1'"
                size="mini"
                type="text"
                icon="el-icon-refresh-left"
                @click="handleRefund(scope.row)"
                v-hasPermi="['payment:order:refund']"
              >退款</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <el-tab-pane label="支付宝订单" name="alipay">
        <el-table v-loading="loading" :data="alipayOrderList">
          <el-table-column label="商户订单号" align="center" prop="outTradeNo" width="200" show-overflow-tooltip />
          <el-table-column label="支付宝订单号" align="center" prop="transactionId" width="280" show-overflow-tooltip />
          <el-table-column label="商品描述" align="center" prop="description" width="150" show-overflow-tooltip />
          <el-table-column label="订单金额" align="center" prop="totalAmount" width="100">
            <template slot-scope="scope">
              <span>¥{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center" prop="status" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === '0'" type="warning">待支付</el-tag>
              <el-tag v-else-if="scope.row.status === '1'" type="success">支付成功</el-tag>
              <el-tag v-else-if="scope.row.status === '2'" type="danger">支付失败</el-tag>
              <el-tag v-else-if="scope.row.status === '3'" type="info">已退款</el-tag>
              <el-tag v-else-if="scope.row.status === '4'" type="info">已关闭</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="支付时间" align="center" prop="payTime" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.payTime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['payment:order:query']"
              >详情</el-button>
              <el-button
                v-if="scope.row.status === '1'"
                size="mini"
                type="text"
                icon="el-icon-refresh-left"
                @click="handleRefund(scope.row)"
                v-hasPermi="['payment:order:refund']"
              >退款</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

        <!-- 订单详情对话框 -->
        <el-dialog title="订单详情" :visible.sync="open" width="900px" append-to-body class="order-detail-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商户订单号" prop="outTradeNo">
          <el-input v-model="form.outTradeNo" :disabled="true" class="no-wrap-input" />
        </el-form-item>
        <el-form-item label="微信订单号" prop="transactionId" v-if="activeTab === 'wechat'">
          <el-input v-model="form.transactionId" :disabled="true" class="no-wrap-input" />
        </el-form-item>
        <el-form-item label="支付宝订单号" prop="transactionId" v-if="activeTab === 'alipay'">
          <el-input v-model="form.transactionId" :disabled="true" class="no-wrap-input" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" :disabled="true" />
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" :disabled="true" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" :disabled="true">
            <el-option label="待支付" value="0" />
            <el-option label="支付成功" value="1" />
            <el-option label="支付失败" value="2" />
            <el-option label="已退款" value="3" />
            <el-option label="已关闭" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-input v-model="form.payTime" :disabled="true" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="form.createTime" :disabled="true" />
        </el-form-item>
        
        <!-- 退款信息区域 -->
        <div v-if="form.status === '3'" class="refund-info-section">
          <el-divider content-position="left">退款信息</el-divider>
          <el-form-item label="退款金额" prop="refundAmount">
            <el-input v-model="form.refundAmount" :disabled="true" />
          </el-form-item>
          <el-form-item label="退款时间" prop="refundTime">
            <el-input v-model="form.refundTime" :disabled="true" />
          </el-form-item>
          <el-form-item label="退款原因" prop="refundReason">
            <el-input v-model="form.refundReason" type="textarea" :disabled="true" :rows="3" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog title="申请退款" :visible.sync="refundOpen" width="500px" append-to-body>
      <el-form ref="refundForm" :model="refundForm" :rules="refundRules" label-width="120px">
        <el-form-item label="商户订单号" prop="outTradeNo">
          <el-input v-model="refundForm.outTradeNo" :disabled="true" />
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input v-model="refundForm.totalAmount" :disabled="true" />
        </el-form-item>
        <el-form-item label="退款金额(元)" prop="refundAmount">
          <el-input-number
            v-model="refundForm.refundAmount"
            :min="0.01"
            :max="refundForm.totalAmount"
            :precision="2"
            :step="0.01"
            style="width: 100%;"
            @change="calculateRefundFee"
          ></el-input-number>
          <div class="refund-note">
            <span style="color: #909399; font-size: 12px;">注意: 退款时会扣除0.3%的手续费</span>
          </div>
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="refundForm.refundReason" type="textarea" :rows="3" placeholder="请输入退款原因"></el-input>
        </el-form-item>
        
        <!-- 手续费计算提示 -->
        <el-alert
          title=""
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;">
          <div slot="title">
            <div style="margin-bottom: 5px;">
              <strong>退款手续费: 0.3%</strong>
            </div>
            <div>
              预计手续费: ¥{{ refundForm.estimatedFee }}元, 实际退款: ¥{{ refundForm.actualRefund }}元
            </div>
          </div>
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRefund">取 消</el-button>
        <el-button type="warning" @click="submitRefund" :loading="refundLoading">确认退款</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWechatOrderList, getAlipayOrderList, refundWechatOrder } from "@/api/payment";
import request, { download } from '@/utils/request';

export default {
  name: "OrderQuery",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 支付宝订单表格数据
      alipayOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outTradeNo: null,
        transactionId: null,
        description: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 当前激活的标签页
      activeTab: 'wechat',
      // 退款对话框
      refundOpen: false,
      refundLoading: false,
      // 退款表单
      refundForm: {
        outTradeNo: null,
        totalAmount: 0,
        refundAmount: 0.01,
        refundReason: '用户申请退款',
        estimatedFee: 0,
        actualRefund: 0
      },
      // 退款表单校验规则
      refundRules: {
        refundAmount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '退款金额必须大于0.01元', trigger: 'blur' }
        ],
        refundReason: [
          { required: true, message: '请输入退款原因', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      // 根据当前标签页选择不同的API
      if (this.activeTab === 'wechat') {
        this.getWechatOrderList();
      } else {
        this.getAlipayOrderList();
      }
    },
    /** 查询微信订单列表 */
    getWechatOrderList() {
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        outTradeNo: this.queryParams.outTradeNo,
        transactionId: this.queryParams.transactionId,
        description: this.queryParams.description,
        status: this.queryParams.status,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      };
      
      // 过滤掉空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === null || params[key] === undefined || params[key] === '') {
          delete params[key];
        }
      });
      
      console.log('微信订单查询参数:', params);
      getWechatOrderList(params).then(response => {
        console.log('微信订单查询响应:', response);
        this.orderList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取微信订单列表失败:', error);
        this.loading = false;
        this.$message.error('获取订单列表失败: ' + (error.message || '未知错误'));
      });
    },
    /** 查询支付宝订单列表 */
    getAlipayOrderList() {
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        outTradeNo: this.queryParams.outTradeNo,
        transactionId: this.queryParams.transactionId,
        description: this.queryParams.description,
        status: this.queryParams.status,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      };
      
      // 过滤掉空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === null || params[key] === undefined || params[key] === '') {
          delete params[key];
        }
      });
      
      console.log('支付宝订单查询参数:', params);
      getAlipayOrderList(params).then(response => {
        console.log('支付宝订单查询响应:', response);
        this.alipayOrderList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取支付宝订单列表失败:', error);
        this.loading = false;
        this.$message.error('获取订单列表失败: ' + (error.message || '未知错误'));
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        outTradeNo: null,
        transactionId: null,
        description: null,
        totalAmount: null,
        status: null,
        payTime: null,
        createTime: null,
        // 退款信息字段
        refundAmount: null,
        refundTime: null,
        refundReason: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 详情按钮操作 */
    handleView(row) {
      this.reset();
      this.form = { ...row };
      this.open = true;
      this.title = "订单详情";
    },
    /** 退款按钮操作 */
    handleRefund(row) {
      this.refundForm.outTradeNo = row.outTradeNo;
      this.refundForm.totalAmount = parseFloat(row.totalAmount);
      this.refundForm.refundAmount = parseFloat(row.totalAmount); // 默认全额退款
      this.refundForm.refundReason = '用户申请退款';
      this.calculateRefundFee();
      this.refundOpen = true;
    },
    
    /** 计算退款手续费 */
    calculateRefundFee() {
      const refundAmount = this.refundForm.refundAmount || 0;
      const feeRate = 0.003; // 0.3%手续费
      this.refundForm.estimatedFee = (refundAmount * feeRate).toFixed(2);
      this.refundForm.actualRefund = (refundAmount - refundAmount * feeRate).toFixed(2);
    },
    
    /** 取消退款 */
    cancelRefund() {
      this.refundOpen = false;
      this.resetRefundForm();
    },
    
    /** 重置退款表单 */
    resetRefundForm() {
      this.refundForm = {
        outTradeNo: null,
        totalAmount: 0,
        refundAmount: 0.01,
        refundReason: '用户申请退款',
        estimatedFee: 0,
        actualRefund: 0
      };
      this.$refs.refundForm && this.$refs.refundForm.resetFields();
    },
    
    /** 提交退款 */
    submitRefund() {
      this.$refs.refundForm.validate(valid => {
        if (valid) {
          this.refundLoading = true;
          const refundData = {
            outTradeNo: this.refundForm.outTradeNo,
            refundAmount: this.refundForm.refundAmount,
            reason: this.refundForm.refundReason
          };
          
          refundWechatOrder(refundData).then(response => {
            this.$message.success('退款申请成功');
            this.refundOpen = false;
            this.resetRefundForm();
            this.getList(); // 刷新列表
          }).catch(error => {
            console.error('退款失败:', error);
            this.$message.error('退款申请失败');
          }).finally(() => {
            this.refundLoading = false;
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 根据当前标签页选择不同的导出接口
      let exportUrl = '';
      let fileName = '';
      
      if (this.activeTab === 'wechat') {
        exportUrl = 'admin/payment/wechat/order/export';
        fileName = `微信订单_${new Date().getTime()}.xlsx`;
      } else {
        exportUrl = 'admin/payment/alipay/order/export';
        fileName = `支付宝订单_${new Date().getTime()}.xlsx`;
      }
      
      // 构建导出参数
      const exportParams = {
        ...this.queryParams,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      };
      
      // 过滤掉空值参数
      Object.keys(exportParams).forEach(key => {
        if (exportParams[key] === null || exportParams[key] === undefined || exportParams[key] === '') {
          delete exportParams[key];
        }
      });
      
      console.log('导出参数:', exportParams);
      
      // 使用系统标准的download方法
      this.download(exportUrl, exportParams, fileName);
    },
    /** 标签页切换 */
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.resetQuery();
    }
  }
};
</script>

<style scoped>
.query-form {
  white-space: nowrap;
  overflow-x: auto;
}

.query-form .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
  display: inline-block;
  vertical-align: top;
}

.query-form .el-form-item:last-child {
  margin-right: 0;
}

/* 确保表单项不会换行 */
.query-form .el-form-item__content {
  display: inline-block;
}

/* 确保标签文字不换行 */
.query-form .el-form-item__label {
  white-space: nowrap;
  word-break: keep-all;
  text-align: left;
}

/* 确保表格单元格内容不换行 */
.el-table .cell {
  white-space: nowrap;
  word-break: keep-all;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 订单详情对话框样式 */
.order-detail-dialog .el-dialog {
  max-width: 90vw;
}

/* 防止输入框内容换行 */
.no-wrap-input .el-input__inner {
  white-space: nowrap;
  word-break: keep-all;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 退款信息区域样式 */
.refund-info-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.refund-info-section .el-divider {
  margin: 0 0 20px 0;
}
</style>